﻿@inject ISnackbar Snackbar
@inject ChatState _chatState
@inject IJSRuntime JS

@implements IDisposable

<div class="d-flex mb-6 pa-2 rounded-lg" style="@BackgroundColorStyle">
    <div id="chat-message-avatar" class="avatar mr-4 mt-1">
        <MudAvatar Rounded="true" Color="Color.Secondary">
            <MudImage Src="@(Message?.Author == "bot" ? !string.IsNullOrEmpty(@_chatState.AssignedAssistant?.AvatarUrl) ? @_chatState.AssignedAssistant?.AvatarUrl : @DefaultAvatarUrl : @_chatState.UserAvatar)" />
        </MudAvatar>
    </div>
    <div id="chat-message-text" class="flex-grow-1">
        <div class="d-flex flex-row">
            <MudText Typo="Typo.inherit" Class="mr-3" Style="font-size: 16px; font-weight: 900;">@(Message?.Author == "bot" ? !string.IsNullOrEmpty(@_chatState.AssignedAssistant?.Name) ? @_chatState.AssignedAssistant.Name : "Assistant’s Ghost" : @_chatState.UserName)</MudText>
            <MudText Typo="Typo.caption" Class="my-auto mt-1">@Message?.Timestamp.ToString("M/d/yyyy 'at' h:mm:ss tt")</MudText>
        </div>
        <div class="pa-2 rounded-sm" style="@BackgroundColorStyle">
            <MudText Typo="Typo.body1" Class="mr-2 mt-2" Style="@BackgroundColorStyle">
                <div class="markdown-content">
                    @((MarkupString)ConvertMarkdownToHtml(Message?.Content))
                </div>
            </MudText>
            <div id="chat-message-icons" class="d-flex flex-row mt-2">
                <MudIconButton id="chat-read-aloud-button" Class="mt-1" Size="Size.Small" Color="Color.Inherit" Disabled="true">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 19" width="20" height="20">
                        <path fill="currentColor" d="M13 2.25c0-1.079-1.274-1.65-2.08-.934L6.427 5.309a.75.75 0 0 1-.498.19H2.25A2.25 2.25 0 0 0 0 7.749v4.497a2.25 2.25 0 0 0 2.25 2.25h3.68a.75.75 0 0 1 .498.19l4.491 3.994c.806.716 2.081.144 2.081-.934V2.25ZM7.425 6.43 11.5 2.807v14.382l-4.075-3.624a2.25 2.25 0 0 0-1.495-.569H2.25a.75.75 0 0 1-.75-.75V7.75a.75.75 0 0 1 .75-.75h3.68a2.25 2.25 0 0 0 1.495-.569Zm9.567-2.533a.75.75 0 0 1 1.049.157A9.959 9.959 0 0 1 20 10a9.96 9.96 0 0 1-1.96 5.946.75.75 0 0 1-1.205-.892A8.459 8.459 0 0 0 18.5 10a8.459 8.459 0 0 0-1.665-5.054.75.75 0 0 1 .157-1.049ZM15.143 6.37a.75.75 0 0 1 1.017.303c.536.99.84 2.125.84 3.328a6.973 6.973 0 0 1-.84 3.328.75.75 0 0 1-1.32-.714c.42-.777.66-1.666.66-2.614s-.24-1.837-.66-2.614a.75.75 0 0 1 .303-1.017Z"></path>
                    </svg>
                </MudIconButton>
                <MudIconButton OnClick="CopyToClipboard" id="chat-copy-message-button" Size="Size.Small" Class="ml-2" Icon="@Icons.Material.Filled.ContentCopy" Color="Color.Inherit" Disabled="false" />
            </div>
        </div>
    </div>
</div>

<style>
    .markdown-content {
        word-wrap: break-word;
    }
    .markdown-content ol,
    .markdown-content ul {
        padding-left: 20px;
        margin-left: .5em; 
    }

    .markdown-content pre {
        padding: 12px;
    }

    .markdown-content code {
        font-weight: bold;
        color: var(--mud-palette-info);
    }

    .mud-icon-button:hover {
        box-shadow: none !important;
        outline: none !important;
    }
</style>

@code 
{
    [Parameter] public ChatMessageResponse? Message { get; set; }
    [CascadingParameter] private bool _IsDarkModeEnabled { get; set; }
    private const string DefaultAvatarUrl = "https://raw.githubusercontent.com/ktutak1337/Stellar-Chat/main/docs/assets/images/_1863a13f-cfb3-454d-ada0-34595b28c2e6.jpg";

    private string BackgroundColorStyle => $"{(Message?.Author == "user" ? $"background-color: {(_IsDarkModeEnabled ? "#2B2B34" : "#f5f5f5")}" : "background-color: var(--mud-palette-background)")};";

    protected override void OnInitialized()
    {
        _chatState.UserNameChanged += StateHasChanged;
        _chatState.UserAvatarChanged += StateHasChanged;
        _chatState.AssignedAssistantChanged += StateHasChanged;
    }

    public void Dispose()
    {
        _chatState.UserNameChanged -= StateHasChanged;
        _chatState.UserAvatarChanged -= StateHasChanged;
        _chatState.AssignedAssistantChanged -= StateHasChanged;
    }

    private string ConvertMarkdownToHtml(string? markdown)
    {
        if (markdown!.IsEmpty())
        {
            return string.Empty;
        }

        var pipeline = new MarkdownPipelineBuilder()
            .UsePipeTables()
            .UseAdvancedExtensions()
            .UseColorCode(styleDictionary: StyleDictionary.DefaultDark)
            .UseAutoLinks()
            .UseEmojiAndSmiley()
            .UseMediaLinks()
            .UseCitations()
            .UsePragmaLines()
            .UseCustomContainers()
            .Build();

        return Markdown.ToHtml(markdown!, pipeline);
    }

    private async Task CopyToClipboard()
    {
        if(Message!.Content.IsNotEmpty())
        {
            await JS.InvokeVoidAsync("navigator.clipboard.writeText", Message?.Content);

            ShowSnackbar("Text copied to clipboard!", Severity.Info);
        }
    }

    private void ShowSnackbar(string message, Severity severity)
    {
        Snackbar.Configuration.PositionClass = Defaults.Classes.Position.TopRight;

        Snackbar.Add(message, severity, options =>
        {
            options.HideTransitionDuration = 100;
        });
    }
}
